package top.boycharse.ftp.server;

import top.boycharse.ftp.server.common.CommandInterpreter;
import top.boycharse.ftp.server.common.ThreadPoolManager;

import java.io.*;
import java.net.Socket;

public abstract class ServerFTPProcess {

    private long id;

    private User user;

    private Socket socket;

    private String tag;

    public final static String QUIT = "quit";

    public ServerFTPProcess(Socket socket,long id) {
        this.id = id;
        this.socket = socket;
        this.tag = socket.getInetAddress().getHostAddress() + ":";
    }

    public void start() {
        ThreadPoolManager.getInstance().execute(new Runnable() {
            @Override
            public void run() {
                BufferedReader reader = null;
                String str = null;
                OutputStream outputStream = null;
                CommandInterpreter commandInterpreter;
                try {
                    outputStream = socket.getOutputStream();
                    commandInterpreter = new CommandInterpreter(outputStream,socket.getInetAddress().getHostAddress(),socket.getPort() + 1);
                    reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                    while ((str = reader.readLine()) != null && !str.toLowerCase().equals(QUIT)) {
                        System.out.println(tag + "发送了一条命令，" + str);
                        commandInterpreter.interpreter(str);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }finally {
                    try {
                        if (socket != null) {
                            socket.close();
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
    }

    public abstract void destroy();

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    public static class User{
        public String userName;
        public String password;
        public boolean isLogin;

        public String getUserName() {
            return userName;
        }

        public void setUserName(String userName) {
            this.userName = userName;
        }

        public String getPassword() {
            return password;
        }

        public void setPassword(String password) {
            this.password = password;
        }

        public boolean isLogin() {
            return isLogin;
        }

        public void setLogin(boolean login) {
            isLogin = login;
        }
    }
}
